package gl.java.sms;

import gl.java.sms.bean.Smser;
import gl.java.sms.util.Result;
import gl.java.sms.util.TextUtils;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import org.apache.log4j.Logger;

import cn.jpush.api.common.APIConnectionException;
import cn.jpush.api.common.APIRequestException;
import cn.jpush.api.push.PushClient;
import cn.jpush.api.push.PushResult;

import com.google.gson.JsonObject;
/**
 * 接受短信发送的请求,将任务放到待发送队列中
 * @author Administrator
 *
 */
@Path("/send")
public class SendSms {

	@GET
	public String send(@QueryParam("tel") String tel,
			@DefaultValue("JLKJ") @QueryParam("content") String conent,
			@QueryParam("token") String token) {
		System.out.println("tel:" + tel);
		System.out.println("conent:" + conent);
		System.out.println("token:" + "fas");
		if (TextUtils.isEmpty(token) /*||!isLogin(token)*/) {
			return Result.formatErrJson("Invalid Token,must login at first");
		}
		if (TextUtils.isEmpty(tel) || tel.length() != 11) {
			return Result.formatErrJson("Invalid Tel");
		}
		if (TextUtils.isEmpty(conent)) {
			return Result.formatErrJson("Invalid Conent");
		}
		return Result.formatJson(
				true,
				/*pushSmsTask(tel, conent, SMS.addWatiingSendSms(tel, conent)
						.getId())*/SMS.addWatiingSendSms(tel, conent).toString(), null);
	}

	private boolean isLogin(String token) {
		return UserList.isHasThisToken(token);
	}

	public static void main(String[] args) throws InterruptedException {
		int i = 0 ;
		while(i<1000){
			i++;
			SendSms.pushSmsTask("15207155981", "test"+i, 0);
			Thread.sleep(10*1000);
		}
		
	}

	private static final String appKey = "37d6567b48ab0666d9547ee4";
	private static final String masterSecret = "fb7dd58fa5f8bed3a5762900";
	private static PushClient pushClient = null;

	/**
	 * 推送短信任务到客户端
	 * 
	 * @param tel
	 * @param content
	 * @param id
	 * @return
	 */
	public static String pushSmsTask(String tel, String content, long id) {
		if (pushClient==null) {
			pushClient = new PushClient(masterSecret, appKey);
		}
		try {
			JsonObject jo = new JsonObject();
			jo.addProperty("platform", "all");
			Smser smser = null;
			int time = 10;
			while (time > 0 && (smser = UserList.getNoBusyUser("0")) == null) {
				time--;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
			if (smser == null) {
				Logger.getLogger("pushSmsTask").error(
						"smser is busy,the count of waiting send:"
								+ SMS.getCountOfWaitingSend());
				return Result.formatErrJson("smser busy");
			}
			if (TextUtils.isEmpty(smser.getName())) {
				jo.addProperty("audience", "all");
			} else {
				//http://docs.jpush.cn/display/dev/Push-API-v3#Push-API-v3-audience
				jo.addProperty("audience","{\"alias\" : [ \""+smser.getName()+"\" ]}");
			}
			JsonObject jo2 = new JsonObject();
			jo2.addProperty("alert", "sendsms");
			jo2.addProperty("title", "title");

			// {"msg_content":{"num":"18672960052","content":"fasdfasf"}}
			JsonObject msg_content = new JsonObject();
			msg_content.addProperty("num", tel);
			msg_content.addProperty("content", content);
			msg_content.addProperty("id", id);

			JsonObject message = new JsonObject();
			message.addProperty("msg_content", msg_content.toString());

			jo.addProperty("notification", jo2.toString());
			jo.addProperty("message", message.toString());
			System.out.println("send:" + jo.toString());
			PushResult result = pushClient.sendPush(jo.toString());
			// set busy state
//			smser.setBusy(true);
			////////////改变策略，无需保证顿新是否送达。值需要保证短信是否发出
			smser.setBusy(false);
			SMS.removeWaitSms(id);
			////////////改变策略，无需保证顿新是否送达。值需要保证短信是否发出
			return result.toString();
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return null;
	}

}